#include "file_list.h"
#include <string.h>
using namespace std;

namespace PFS
{
bool FileList::add_file(const char* file_name, INodeFile* inode)
{ 
    md5.GenerateMD5(file_name, strlen(file_name));
    const char* md5_name = md5.ToString().c_str();
    ITER it = file_list.find(md5_name);
    if(it != file_list.end())
        return false;
    else
        file_list[md5_name] = inode;
}

bool FileList::exist_file(const char* file_name)
{
    md5.GenerateMD5(file_name, strlen(file_name));
    const char* md5_name = md5.ToString().c_str();
    return file_list.count(md5_name) != 0;
}

INodeFile* FileList::find_file(const char* file_name)
{
    md5.GenerateMD5(file_name, strlen(file_name));
    const char* md5_name = md5.ToString().c_str();
    INodeFile* inode = NULL;
    ITER it = file_list.find(md5_name);
    if(it != file_list.end())
        inode = it->second;
    reurn inode;
}

INodeFile* FileList::replace_file(const char* file_name, INodeFile* new_node)
{
    md5.GenerateMD5(file_name, strlen(file_name));
    const char* md5_name = md5.ToString().c_str();
    INodeFile* old_node = NULL;
    ITER it = file_list.find(md5_name);
    if(it != file_list.end())
    {
        old_node = it->second;
        it->second = new_node;
    }
    else
        file_list[md5_name] = new_node;
    return old_node;
}

void FileList::rename_file(const char* old_name, const char* new_name)
{
    md5.GenerateMD5(file_name, strlen(file_name));
    const char* md5_name = md5.ToString().c_str();
    ITER it = file_list.find(md5_name);
    
    md5.GenerateMD5(new_name, strlen(file_name));
    const char* md5_new_name = md5.ToString().c_str();
    if(it != file_list.end())
    {
        file_list[md5_new_name] = it->second;
        file_list.erase(it);
    }
}

void FileList::remove_file(const char* file_name)
{
    md5.GenerateMD5(file_name, strlen(file_name));
    const char* md5_name = md5.ToString().c_str();
    ITER it = file_list.find(md5_name);
    if(it != file_list.end())
    {
        delete it->second;
        file_list.erase(it);
    }
}

}
